﻿//此类用来封装下载的，还没实现
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.AddressableAssets;

public class XDownload
{
    public static string URL = "http://localhost:8000";
    public static string GetPlatformURL()
    {
        return URL + "/" + GameConfig.BuildTarget;// + Application.buil
    }
    //在AddressableAssetSetting内勾选Disable Catalog Update On Startup。

    //然后用下面的代码做了测试：
#if false
var initHandle = Addressables.InitializeAsync();
yield return initHandle;
var handler = Addressables.CheckForCatalogUpdates(false);
yield return handler;
var catalogs = handler.Result;
Debug.Log($"need update catalog:{catalogs.Count}");
foreach (var catalog in catalogs) {
   Debug.Log(catalog);
}

if (catalogs.Count > 0) {
    var updateHandle = Addressables.UpdateCatalogs(catalogs, false);
    yield return updateHandle;
    var locators = updateHandle.Result;
    foreach (var locator in locators) {
        foreach (var key in locator.Keys) {
            Debug.Log($"update {key}");
        }
    }
}
Addressables.Release(handler);

#endif

    //不过一般来说做启动更新检测只要使用Download相关的2个函数就可以了，大致如下：
#if false
var sizeHandle = Addressables.GetDownloadSizeAsync(keys);
yield return sizeHandle;
long totalDownloadSize = sizeHandle.Result;
if (totalDownloadSize > 0) {
    var downloadHandle =  Addressables.DownloadDependenciesAsync(keys, Addressables.MergeMode.Union);
    while (!downloadHandle.IsDone) {
        float percent = downloadHandle.PercentComplete;
        Debug.Log($"已经下载：{(int) (totalDownloadSize * percent)}/{totalDownloadSize}");
    }
}
#endif
}


//制定资源从哪里加载
#if fale
// 来自其他工程的Addressable资源的catalog*.json文件路径
var catalogPath = @"D:\UnityProjects\AddressablesTest\Mods\mod_01\catalog_2020.03.09.05.54.27.json";

// 加载catalog，并在加载完成事件回调中进行资源加载
Addressables.LoadContentCatalogAsync(catalogPath).Completed += (resLocatorAopHandler) =>
{
    // 要加载的资源
    var assetKey = "Assets/ModAssets/Prefabs/cube_01.prefab";

    // 可以直接进行全局查找并加载
    //Addressables.InstantiateAsync(assetKey);

    // 也可以只在本次加载的Catalog数据中查找并加载（理论上性能应该更好，没有见到相关文档）
    if (resLocatorAopHandler.Result.Locate(assetKey, typeof(GameObject), out var locations))
    {
        var resourceLocation = locations[0];
        Addressables.InstantiateAsync(resourceLocation);
    }
};

#endif
